package com.jiyinit.web.core.business.service;

import java.util.*;

import javax.annotation.Resource;

import com.jiyinit.web.core.business.dao.TabSendMessageDao;
import com.jiyinit.web.core.business.entity.*;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.enums.OperationTypeConstant;
import com.jiyinit.web.core.business.enums.SystemConstant;
import org.springframework.stereotype.Service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.web.core.business.dao.TabCoreTaskDao;
import com.jiyinit.web.core.business.dao.TabCoreUserDao;
import com.jiyinit.web.core.business.dao.TabCoreUserTaskDao;
import com.jiyinit.web.core.business.dto.TaskRequest;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.vo.TaskInfoVo;
import com.jiyinit.web.core.business.vo.UserInfoVo;
import com.jiyinit.web.core.business.vo.UserTaskVo;
import com.jiyinit.web.core.common.util.MessagePush;
import com.jiyinit.web.core.common.util.UserUtil;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author wuyuefeng
 * @version 1.0
 * @date 2017/4/11 17:59
 * @since 1.0
 */
@Service("core.taskServiceImpl")
public class TaskServiceImpl {
	
	@Resource(name = "core.tabCoreTaskDao")
    private TabCoreTaskDao tabCoreTaskDao;
	@Resource(name = "core.tabCoreUserTaskDao")
	private TabCoreUserTaskDao tabCoreUserTaskDao;

    @Resource(name = "send.tabSendMessageDao")
    private TabSendMessageDao tabSendMessageDao;

    public List<TabCoreTask> findTaskByIds(List<TabSendMessageEntity> mesList){
        return tabCoreTaskDao.findTaskByIds(mesList);
    }
	
	 /**
     * 分页查询用户信息
     * @author wuyuefeng
     * @create 2017/4/13 9:00
     * @param taskRequest
     * @return
     */
    public PagingResult<TaskInfoVo> findTasksByCons(TaskRequest taskRequest){
        return tabCoreTaskDao.findTasksAndAlloters(taskRequest);
    }
    
    
    public PagingResult<TaskInfoVo> findTasksBycreateUid(TaskRequest taskRequest){
        return tabCoreTaskDao.findTasksByCons(taskRequest);
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:20:09
         * @param 
         * @return
     */
    public PagingResult<TaskInfoVo> findMyTasksByCons(TaskRequest taskRequest){
        return tabCoreTaskDao.findMyTasksByCons(taskRequest);
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月3日 上午10:20:09
         * @param 
         * @return
     */
    public PagingResult<TaskInfoVo> findTasksAndAlloters(TaskRequest taskRequest){
        return tabCoreTaskDao.findTasksAndAlloters(taskRequest);
    }
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:53:51
         * @param 
         * @return Integer
     */
    public int addTask(TabCoreTask tabCoreTask) {
        int num = tabCoreTaskDao.addTask(tabCoreTask);
        return num;
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月25日 下午5:54:00
         * @param 
         * @return TabCoreTask
     */
    public TabCoreTask findTaskById(Integer taskId) {
        TabCoreTask tabCoreTask = null;
        tabCoreTask = tabCoreTaskDao.findTaskById(taskId);		
        return tabCoreTask;
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月4日 下午3:19:45
         * @param 
         * @return
     */
    public List<TabCoreTask> findTaskByTitle(String title) {
    	List<TabCoreTask> tabCoreTasks = new ArrayList<TabCoreTask>();
    	tabCoreTasks = tabCoreTaskDao.findTaskByTitle(title);		
        return tabCoreTasks;
    }
    
    
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 上午11:06:14
         * @param 
         * @return
     */
    public int updateTask(TabCoreTask tabCoreTask) {
        int num = tabCoreTaskDao.updateTaskById(tabCoreTask);
        return num;
    }
    /**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年4月26日 下午2:48:50
         * @param 
         * @return
     */
    public String deleteTask(Integer[] taskIds) {
    	String status = null;
    	List<TaskInfoVo> taskInfoVos = new ArrayList<TaskInfoVo>();
    	taskInfoVos = tabCoreTaskDao.findChildsByid(taskIds);
    	//有子任务
    	if(taskInfoVos.size()>0){
    		status = "child";
    	}
    	List<UserTaskVo> userTaskVos = new ArrayList<UserTaskVo>();
    	userTaskVos = tabCoreUserTaskDao.findUserTasksByTaskId(taskIds);
    	//任务已分配
    	if(userTaskVos.size()>0){
    		status = "distribute";;
    	}
    	
    	int num = tabCoreTaskDao.deleteTaskByIds(taskIds);
    	if(num>0)
    		return "ok";
    	return "failed";
    }
    
    public boolean findChildsById(Integer taskId){
    	boolean flag = false;
    	
    	
    	return flag;
    }
	/**
	     * 说明
	     * @author wuyuefeng
	     * @create 2017年5月10日 上午11:38:09
	     * @param 
	     * @return
	     */
	public int addTaskAndUser(TabCoreTask tabCoreTask,Integer[] userIds,TaskRequest taskRequest,String type) {
		int taskId = 0;
        int num = 0;
        Integer createId = 0;
		if(tabCoreTask.getTaskId()!=null&&tabCoreTask.getTaskId() != 0){
			taskId = tabCoreTask.getTaskId();
            createId =tabCoreTask.getCreateUid();
            num = updateTask(tabCoreTask);
		}else{
			num = tabCoreTaskDao.addTask(tabCoreTask);
            taskId = tabCoreTask.getTaskId();
            if(taskRequest.getCreateUid() != null)
            {createId = taskRequest.getCreateUid();}
            else{
                createId = UserUtil.getCurrentUser().getUserId();
            }
		}
		

        //根据任务Id查询，任务的参与人员，区分出变动的人员
        List<TabCoreUserTask>  deleteList = new ArrayList<>();
        List<TabCoreUserTask> list = tabCoreUserTaskDao.getUserByTaskId(tabCoreTask.getTaskId());
        for(TabCoreUserTask task: list){
            Boolean isExist = false;
            for(int i = 0 ;i <= userIds.length-1; i++){
                if(task.getAlloterId().intValue() == userIds[i].intValue()) {isExist = true; break;}
            }
            if(!isExist) deleteList.add(task);
        }
        for(TabCoreUserTask deleteTask:deleteList){
            tabCoreUserTaskDao.delete(deleteTask);
        }

        StringBuffer  addUser = new StringBuffer();
        for(int i = 0 ;i <= userIds.length-1; i++) {
            Boolean addFlag = true;
            for(TabCoreUserTask task: list){
                if(task.getAlloterId().intValue() == userIds[i].intValue()) {addFlag = false; break;}
            }
            if(addFlag){
                addUser.append(userIds[i]).append(",");
            }
        }
        String users="";
        String[] allotIds=new String[]{};
        if(addUser.toString().length()>0)
        {
            users = addUser.toString().substring(0,addUser.toString().length()-1);
            allotIds = users.split(",");
        }

		if(taskId > 0){
			for(int i=0;i<allotIds.length;i++){
				TabCoreUserTask tabCoreUserTask = new TabCoreUserTask();
	    		Date alloterEndPl = taskRequest.getAEndPl();
	            String alloterDesc = taskRequest.getADesc();
	            Date alloterStarPl = taskRequest.getAStartPl();
	            tabCoreUserTask.setAlloterId(new Integer(allotIds[i]));
	            tabCoreUserTask.setStartTimePl(alloterStarPl);
	            tabCoreUserTask.setEndTimePl(alloterEndPl);
	            tabCoreUserTask.setUserTaskDes(alloterDesc);
	            tabCoreUserTask.setCreateTime(new Date());
	            tabCoreUserTask.setTaskId(tabCoreTask.getTaskId());
				tabCoreUserTaskDao.addUserTask(tabCoreUserTask);
			}
		}

		Map<String,String> returnStr = new HashMap<>();
		
		returnStr.put("taskTitle", tabCoreTask.getTitle());
		returnStr.put("taskId", tabCoreTask.getTaskId().toString());
		returnStr.put("createUid", tabCoreTask.getCreateUid().toString());
		returnStr.put("strikeType", "2");
		returnStr.put("type",type);
		returnStr.put("dsc", tabCoreTask.getDescription());
		returnStr.put("taskStatus",taskRequest.getTaskStatus());
		//returnStr.put("content", taskRequest.getTitle());
        if(OperationTypeConstant.TASK_ADD.equals(type))
        {
            returnStr.put("content", "新增任务："+tabCoreTask.getTitle());
        }
        else if(OperationTypeConstant.TASK_CHANGE_PERSON.equals(type))
        {
            returnStr.put("content","任务："+tabCoreTask.getTitle()+"，变更参与人");
        }
        else if(OperationTypeConstant.TASK_ADD_MESSAGE.equals(type))
        {
            returnStr.put("content","任务："+tabCoreTask.getTitle()+"，有内容更新");
        }
        else
        {
            returnStr.put("content",tabCoreTask.getTitle());
        }

        returnStr.put("taskCla", String.valueOf(SystemConstant.SIMPLE_TASK));

        //根据分配人员，生成message
        StringBuffer sendUserIds = new StringBuffer();
        List<Integer> userIList=new ArrayList<Integer>();
        for(Integer userId: userIds){
            if(userIList.contains(userId))
            {
                continue;
            }
            userIList.add(userId);
            sendUserIds.append(userId).append(",");
        }
        String sendUserStr =sendUserIds.substring(0,sendUserIds.toString().length()-1);
        String[] sendUserstemp = sendUserStr.split(",");
        //String[] sendUsers = new String[sendUserstemp.length+1];
        String[] sendUsers = new String[sendUserstemp.length];
        System.arraycopy(sendUserstemp, 0, sendUsers, 0, sendUserstemp.length);
        //sendUsers[sendUserstemp.length] = createId.toString();
        if(taskRequest.getUserId() == null) taskRequest.setUserId(UserUtil.getCurrentUser().getUserId());

        //变更参与人时，不需要向各个参与人发送默认未读消息,否则任务的说说已读未读状态有问题
        String[] sendNoReadMessageUsers=OperationTypeConstant.TASK_CHANGE_PERSON.equals(type)?allotIds:sendUsers;
        List<TabSendMessageEntity> mesList = new ArrayList<TabSendMessageEntity>();
        for( String uid: sendNoReadMessageUsers){
            if((new Integer(uid)).intValue() == taskRequest.getUserId() ) continue;
            TabSendMessageEntity message = new TabSendMessageEntity();
            message.setTaskId(taskId);
            message.setFunId(SystemConstant.SIMPLE_TASK);
            message.setReceiveUserId(new Integer(uid));
            message.setIsRead(CommonEnum.IsRead.NOREAD.getCode());
            message.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
            message.setCreateId(taskRequest.getCreateUid());
            message.setCreateTime(new Date());
            mesList.add(message);
        }
        if(mesList != null && mesList.size() >0) tabSendMessageDao.batchInsert(mesList);

		if(taskRequest.getChannel()!=null&&taskRequest.getChannel().equals("01")){
			MessagePush messagePush = new MessagePush(returnStr,sendUsers);
		}else{
			MessagePush messagePush = new MessagePush(returnStr,sendUsers,"andriod");
		}
        return num;
	}
	
	
	/**
     * 
         * 说明
         * @author wuyuefeng
         * @create 2017年5月11日 上午9:15:19
         * @param 
         * @return
     */
    public PagingResult<TaskInfoVo> findAllMyTasks(TaskRequest taskRequest){
    	return tabCoreTaskDao.findAllMyTasks(taskRequest);
    }

    public PagingResult<TaskInfoVo> findTasksByConditions(TaskRequest taskRequest){
        return tabCoreTaskDao.findTasksByConditions(taskRequest);
    }

    public TabCoreTask findTaskIdByTaskCla(List<Integer> list){
        return tabCoreTaskDao.findTaskIdByTaskCla(list);
    }

    public List<TabCoreTask> findTaskIdByTaskCla(){
        return tabCoreTaskDao.findTaskIdByTaskCla();
    }

    public int insertUserTimed(TabCoreTask coreTask){
        return tabCoreUserTaskDao.insertUserTimed(coreTask);
    }
}
